﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.PinanAPI;
using ZBJF.Warranty.PinanAPI.Model;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu;

namespace ZBJF.Warranty.WebProvider
{
    public class InsuranceOrderProvider
    {
        #region 保单审核
        /// <summary>
        /// 保单审核
        /// </summary>
        /// <param name="insuranceOrderId">保单ID</param>
        /// <param name="isPass">是否审核通过</param>
        /// <param name="checkRemark">审核备注</param>
        /// <param name="opUserAccount">操作人账号</param>
        /// <param name="opUserName">操作人</param>
        /// <param name="lastModifyTime">最后修改时间；用于做并发控制， 防止审核期间保险订单发生改变</param>
        /// <param name="msg">返回的信息</param>
        /// <returns></returns>
        public static bool AuditInsuranceOrder(long insuranceOrderId, bool isPass, string checkRemark, string opUserAccount, string opUserName, DateTime lastModifyTime, ref string msg)
        {
            var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByID(insuranceOrderId);

            //销售商是福建尺度
            if (order.SaleVendorId.HasValue && order.SaleVendorId.Value == (long)SaleVendorEnums.FuJianChiDu)
                return ChiDuCheck(insuranceOrderId, isPass, checkRemark, opUserAccount, opUserName, lastModifyTime, order.SaleVendorId.Value, order.ThirdUniqueNumber, ref msg);
            //平安卡
            else if (order.CardFromType == (byte)InsuranceCardType.Pinan)
                return PingAnCheck(order, insuranceOrderId, isPass, checkRemark, opUserAccount, opUserName, ref msg);
            //中保
            else
                return ZhongBaoCheck(order, insuranceOrderId, isPass, checkRemark, opUserAccount, opUserName, ref msg);
        }
        #endregion


        #region 中保审核
        private static bool ZhongBaoCheck(InsuranceOrder order, long insuranceOrderId, bool isPass, string checkRemark, string opUserAccount, string opUserName, ref string msg)
        {
            //审核通过需要修改的一些信息
            if (isPass)
            {
                order.ThirdUniqueNumber = "ZBJF" + CommonMethod.GetTimeStamp();
                order.ThirdOrderNO = order.ThirdUniqueNumber;
                order.ServiceStartTime = CommonMethod.GetServiceStartTime(DateTime.Now, order.WaitDays); //服务开始时间:核保成功时间+生效等待期
                order.ServiceEndTime = CommonMethod.GetServiceEndTime(order.ServiceStartTime.Value, order.PolicyPeriodYear, order.PolicyPeriodMonth, order.PolicyPeriodDay); //服务结束时间： 服务开始时间+承保日期
                order.OrderStatus = (byte)InsuranceOrderStatus.ApprovedAndPassed;
            }
            else
            {
                order.OrderStatus = (byte)InsuranceOrderStatus.ApprovedButNotPassed;
            }
            order.LastCheckUser = opUserName;
            order.LastCheckTime = DateTime.Now;


            //更新订单信息
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    bool flag = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(order);
                    if (!flag)
                    {
                        ts.Dispose();
                        msg = "操作失败！";
                        return false;
                    }
                    //添加审核日志
                    if (!AddCheckLog(insuranceOrderId, checkRemark, isPass, opUserAccount, opUserName))
                    {
                        ts.Dispose();
                        msg = "操作失败,添加日志不成功！";
                        return false;
                    }

                    ts.Complete();
                    msg = "操作成功";
                    return true;

                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    msg = "操作失败！";
                    CommonMethod.WriteLogs(string.Format("审核订单异常,Data-insuranceOrderId：{0},isPass:{1},checkRemark:{2},opUserAccount:{3},opUserName:{4}", insuranceOrderId, isPass, checkRemark, opUserAccount, opUserName) + ex.Message + ex.StackTrace);
                    return false;
                }
            }
        }
        #endregion

        #region 平安审核
        private static bool PingAnCheck(InsuranceOrder order, long insuranceOrderId, bool isPass, string checkRemark, string opUserAccount, string opUserName, ref string msg)
        {
            //审核通过需要修改的一些信息
            if (isPass)
            {
                order.OrderStatus = (byte)InsuranceOrderStatus.ApprovedAndPassed;
                var retObj = string.Empty;
                //根据订单 判断 是否需要向平安 投保 TODO
                var createPinanPolicyFlag = InsuranceService.CreatePolicyByCard(ref order, ref retObj);
                if (!createPinanPolicyFlag)
                {
                    msg = retObj;
                    return false;
                }
            }
            else
                order.OrderStatus = (byte)InsuranceOrderStatus.ApprovedButNotPassed;

            order.LastCheckUser = opUserName;
            order.LastCheckTime = DateTime.Now;
            //更新订单信息
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    bool flag = ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(order);
                    if (!flag)
                    {
                        ts.Dispose();
                        msg = "操作失败！";
                        return false;
                    }
                    //添加审核日志
                    if (!AddCheckLog(insuranceOrderId, checkRemark, isPass, opUserAccount, opUserName))
                    {
                        ts.Dispose();
                        msg = "操作失败,添加日志不成功！";
                        return false;
                    }

                    ts.Complete();
                    msg = "操作成功";
                    return true;
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    msg = "操作失败！";
                    CommonMethod.WriteLogs(string.Format("审核订单异常,Data-insuranceOrderId：{0},isPass:{1},checkRemark:{2},opUserAccount:{3},opUserName:{4}", insuranceOrderId, isPass, checkRemark, opUserAccount, opUserName) + ex.Message + ex.StackTrace);
                    return false;
                }
            }

        }
        #endregion

        #region 尺度审核
        private static bool ChiDuCheck(long insuranceOrderId, bool isPass, string checkRemark, string opUserAccount, string opUserName, DateTime lastModifyTime, long saleVendorId, string thirdUniqueNumber, ref string msg)
        {
            //需要做并发控制（根据最后修改时间）
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    bool flag = ServiceFactory.InsuranceOrderServiceInstance.UpdateInsuranceOrderStatus(insuranceOrderId, isPass, lastModifyTime, opUserName);
                    if (!flag)
                    {
                        ts.Dispose();
                        msg = "操作失败！";
                        return false;
                    }
                    //添加审核日志
                    if (!AddCheckLog(insuranceOrderId, checkRemark, isPass, opUserAccount, opUserName))
                    {
                        ts.Dispose();
                        msg = "操作失败,添加日志不成功！";
                        return false;
                    }

                    //获取销售商信息
                    Sellers sellerInfo = ServiceFactory.SellersServiceInstance.LoadByID(Convert.ToInt64(saleVendorId));
                    ChiDuDataInteraction chidu = new ChiDuDataInteraction(sellerInfo.SellerInterfaceSecretKey, sellerInfo.SellerInterfaceUrl);
                    //调用尺度接口，通知审核结果
                    Task<bool> re = chidu.InvokeChiduCheckResultInterface(thirdUniqueNumber, flag, checkRemark);
                    if (!re.Result)
                    {
                        ts.Dispose();
                        msg = "操作失败,通知尺度失败！";
                        return false;
                    }
                    ts.Complete();
                    msg = "操作成功";
                    return true;
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    msg = "操作失败！";
                    CommonMethod.WriteLogs(string.Format("审核订单异常,Data-insuranceOrderId：{0},isPass:{1},checkRemark:{2},opUserAccount:{3},opUserName:{4}", insuranceOrderId, isPass, checkRemark, opUserAccount, opUserName) + ex.Message + ex.StackTrace);
                    return false;
                }
            }
        }
        #endregion

        #region 添加审核日志 +  bool AddCheckLog(long insuranceOrderId, string checkRemark, bool isPass, string opUserAccount, string opUserName)
        private static bool AddCheckLog(long insuranceOrderId, string checkRemark, bool isPass, string opUserAccount, string opUserName)
        {
            //添加审核日志
            var obj = ServiceFactory.InsuranceOrderCheckLogServiceInstance.AddEntities(new InsuranceOrderCheckLog()
            {
                InsuranceOrderId = insuranceOrderId,
                CheckRemark = checkRemark,
                CheckResult = isPass,
                CheckTime = DateTime.Now,
                CheckUserAccount = opUserAccount,
                CheckUserName = opUserName
            });
            return obj.ID > 0;
        }
        #endregion
    }
}
